﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;

namespace Core
{
    public static class Common
    {
        static System.Timers.Timer _timer = new System.Timers.Timer(1000 * 30);
        static WebClient wc = new WebClient();
        static string _timestamp = string.Empty;
        static Common()
        {
            if (!_timer.Enabled)
            {
                _timer.Elapsed += new ElapsedEventHandler(Second_Elapsed);
                _timer.AutoReset = true;
                _timer.Interval = 1000 * 15;
                _timer.Enabled = true;
                Second_Elapsed(null, null);
            }
        }
        public static List<string> GetIP()
        {
            System.Net.IPAddress[] addressList = Dns.GetHostAddresses(Dns.GetHostName());
            List<string> ips = new List<string>();
            foreach (IPAddress ip in addressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                    ips.Add(ip.ToString());
            }
            return ips;
        }
        public static bool IsFilePath(this string str)
        {
            if (string.IsNullOrEmpty(str))
                return false;
            return Regex.IsMatch(str, @"^(/.*)+[.].+$");
        }
        /// <summary>
        /// 课堂批注图片格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsPreparingNotationPic(this string str)
        {
            if (string.IsNullOrEmpty(str))
                return false;
            //批注名称约定 备课编号_老师编号_课件编号_PPT页码索引.png 
            return Regex.IsMatch(str, @"^\d+[_]\d+[_]\d+[_]\d+([_]\d+)?[.]\w+$");
        }
        /// <summary>
        /// 课堂生成资源格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsClassRes(this string str)
        {
            if (string.IsNullOrEmpty(str))
                return false;
            //课堂资源名称约定 备课编号_老师编号.xxx
            return Regex.IsMatch(str, @"^Res[_]\d+[_]\d+([_]\d+)?[.]\w+$", RegexOptions.IgnoreCase);
        }
        /// <summary>
        /// 是否为共享目录
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsFileShareDir(this string str)
        {
            if (string.IsNullOrEmpty(str))
                return false;
            return Regex.IsMatch(str, "^\\\\(\\\\[^\\\\/^:?\"|<>]+?\\\\?)+$");
        }
        public static void RequestAdministratorPrivileges(Action<string[]> Run, string[] Args)
        {
            /** 
            * 当前用户是管理员的时候，直接启动应用程序 
            * 如果不是管理员，则使用启动对象启动程序，以确保使用管理员身份运行 
            */
            //获得当前登录的Windows用户标示  
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            //创建Windows用户主题  
            Application.EnableVisualStyles();

            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员  
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //如果是管理员，则直接运行  
                Application.EnableVisualStyles();
                Run(Args);
            }
            else
            {
                //创建启动对象  
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                //设置运行文件  
                startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
                //设置启动参数  
                startInfo.Arguments = String.Join(" ", Args);
                //设置启动动作,确保以管理员身份运行  
                startInfo.Verb = "runas";
                //如果不是管理员，则启动UAC  
                System.Diagnostics.Process.Start(startInfo);
                //退出  
                System.Windows.Forms.Application.Exit();
            }
        }

        /// <summary>  
        /// 执行DOS命令，返回DOS命令的输出  
        /// </summary>  
        /// <param name="dosCommand">dos命令</param>  
        /// <param name="milliseconds">等待命令执行的时间（单位：毫秒），  
        /// 如果设定为0，则无限等待</param>  
        /// <returns>返回DOS命令的输出</returns>  
        public static string Execute(string command, int seconds)
        {
            string output = ""; //输出字符串  
            if (command != null && !command.Equals(""))
            {
                Process process = new Process();//创建进程对象  
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "cmd.exe";//设定需要执行的命令  
                startInfo.Arguments = "/C " + command;//“/C”表示执行完命令后马上退出  
                startInfo.UseShellExecute = false;//不使用系统外壳程序启动 
                startInfo.RedirectStandardInput = false;//不重定向输入  
                startInfo.RedirectStandardOutput = true; //重定向输出  
                startInfo.CreateNoWindow = true;//不创建窗口  
                process.StartInfo = startInfo;
                try
                {
                    if (process.Start())//开始进程  
                    {
                        if (seconds == 0)
                        {
                            process.WaitForExit();//这里无限等待进程结束  
                        }
                        else
                        {
                            process.WaitForExit(seconds); //等待进程结束，等待时间为指定的毫秒  
                        }
                        output = process.StandardOutput.ReadToEnd();//读取进程的输出  
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);//捕获异常，输出异常信息
                }
                finally
                {
                    if (process != null)
                        process.Close();
                }
            }
            return output;
        }

        /// <summary>
        /// 时间截
        /// </summary>
        public static string TimeStamp { get { return _timestamp; } set { _timestamp = value; } }

        private static void Second_Elapsed(object o, ElapsedEventArgs e)
        {
            try
            {
                _timestamp = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Resources/File/TimeStamp");
            }
            catch
            {
                _timestamp = DateTime.Now.Ticks.ToString();
                Log.errorlog(new Exception("获取服务器时间戳失败，已经设置为本地时间戳！"));
            }

        }
    }
}
